package com.delianna.bwt.models;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * @author Delio Castillo (jangeador@gmail.com)
 *
 */
public class BWT implements Parcelable {

	private ArrayList<Port> _ports;
	public String last_updated_date;
	public String last_updated_time;
	public String number_of_ports;
	
	

	public BWT() {
		_ports = new ArrayList<Port>();
	}

	public List<Port> ports() {
		return _ports;
	}

	public List<Port> getFavoritePorts(String favoritePortNumbers) {
		// Return ports from the portID, format
		// (portnumber1,portnumber2,portnumbern)

		ArrayList<Port> favoritePorts = new ArrayList<Port>();
		Port p;
		String[] portNums = favoritePortNumbers.split(",");

		for (String pn : portNums) {
			p = getPort(pn);
			if (p != null) {
				favoritePorts.add(p);
			}
		}
		return favoritePorts;
	}

	public void addPort(Port p) {
		_ports.add(p);
	}

	public void sortPorts() {
		List<Port> p = this.ports();
		Collections.sort(p, new Comparator<Port>() {
			public int compare(Port o1, Port o2) {
				return o1.port_name.compareToIgnoreCase(o2.port_name);
			}
		});
	}

	public Port getPort(String id) {
		for (Port p : _ports) {
			if (p.port_number.equals(id)) {
				return p;
			}
		}
		return null;
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	public BWT(Parcel in) {
		_ports = new ArrayList<Port>();
		readFromParcel(in);
	}

	private void readFromParcel(Parcel in) {
		// TODO Auto-generated method stub

		// Load list of Ports
		Parcelable[] parcelablePorts;
		parcelablePorts = in.readParcelableArray(Port[].class.getClassLoader());
		for (Parcelable par : parcelablePorts) {
			_ports.add((Port) par);
		}

		this.last_updated_date = in.readString();
		this.last_updated_time = in.readString();
		this.number_of_ports = in.readString();
	}

	@Override
	public void writeToParcel(Parcel out, int flags) {
		// TODO Auto-generated method stub
		Port[] ps = new Port[_ports.size()];
		ps = _ports.toArray(ps);

		out.writeParcelableArray(ps, flags);
		out.writeString(last_updated_date);
		out.writeString(last_updated_time);
		out.writeString(number_of_ports);
	}


	public static final Parcelable.Creator<BWT> CREATOR = new Parcelable.Creator<BWT>() {
		public BWT createFromParcel(Parcel in) {
			return new BWT(in);
		}

		public BWT[] newArray(int size) {
			return new BWT[size];
		}
	};
}
